const db = require('../db/index')

//获取所有联系人
exports.getContacts=(req,res)=>{
    const sql=`select * from contacts where userId=? order by lastTime desc`
    db.query(sql, req.user.id, (err, results) => {
        if (err) return res.cc(err)

        // console.log(results)
        return res.send({
            status: 0,
            message: '获取成功！',
            data:results
        })
    })
}

// //获取最近的联系人
// exports.getLastContacts=(req,res)=>{
//     const sql=`select * from chat where pub_id=? or receive_id=?`
//     db.query(sql, [req.user.id,req.user.id], (err, results) => {
//         if (err) return res.cc(err)

//         // console.log(results)
//         return res.send({
//             status: 0,
//             message: '获取成功！',
//             data:results
//         })
//     })
// }

//搜索联系人
exports.searchContacts=(req,res)=>{
    const sql=`select * from contacts where userId=? and peopleName like ? `
    db.query(sql, [req.user.id,`%${req.query.peopleName}%`], (err, results) => {
        if (err) return res.cc(err )

        // console.log(req.query,results)
        return res.send({
            status: 0,
            message: '获取成功！',
            data:results
        })
    })
}

//获取聊天记录
exports.showHistoryMessage=(req,res)=>{
    const sql=`select * from chat where (pub_id=? and receive_id = ?) or (pub_id=? and receive_id = ?) order by time asc`
    db.query(sql, [req.user.id,req.query.peopleId,req.query.peopleId,req.user.id], (err, results) => {
        if (err) return res.cc(err )

        // console.log(req.query,results)
        return res.send({
            status: 0,
            message: '获取成功！',
            data:results
        })
    })
}

//更新contacts表中的unread字段
exports.updateUnread=(req,res)=>{
    const sql=`update contacts set unRead = ? where userId=? and peopleId = ? `
    db.query(sql, [req.body.unRead,req.user.id,req.body.peopleId], (err, results) => {
        if (err) return res.cc(err )

        // console.log(req.query,results)
        return res.send({
            status: 0,
            message: '更新成功！'
        })
    })
}